﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Data.Entity;

namespace DNA.Mvc.Data.Entity
{
    public abstract class UnitOfWorkBase<TDBContext> : IUnitOfWork
        where TDBContext :DbContext
    {
        protected TDBContext dbContext;

        protected abstract EntityRepositoryBase<TDBContext, T> GenericRepostory<T>() where T : class;

        public T GetByID<T>(object id) where T : class
        {
            return GenericRepostory<T>().Find(id);
        }

        public T Add<T>(T t) where T : class
        {
            return GenericRepostory<T>().Create(t);
        }

        public void Update<T>(T t) where T : class
        {
            GenericRepostory<T>().Update(t);
        }

        public void Delete<T>(T t) where T : class
        {
            GenericRepostory<T>().Delete(t);
        }

        public int SaveChanges(bool validateOnSave = true)
        {
            if (!validateOnSave)
                dbContext.Configuration.ValidateOnSaveEnabled = false;

            return dbContext.SaveChanges();
        }

        public void Dispose()
        {
            if (dbContext != null)
                dbContext.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}
